package com.example.xiongan_app_yy.activity;


import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.DotOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.district.DistrictResult;
import com.baidu.mapapi.search.district.DistrictSearch;
import com.baidu.mapapi.search.district.DistrictSearchOption;
import com.baidu.mapapi.search.district.OnGetDistricSearchResultListener;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.example.xiongan_app_yy.R;
import com.example.xiongan_app_yy.adapter.MyAdapter;
import com.example.xiongan_app_yy.listener.OnMapItemClickListener;
import com.example.xiongan_app_yy.plugin.FlutterPluginCounter;
import com.example.xiongan_app_yy.utils.StatusBarUtil;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.util.ArrayList;
import java.util.List;

public class MapActivity extends AppCompatActivity {

    private MapView mMapView;
    private RelativeLayout mTitle;
    private ImageView mBack;
    public BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 123;
    private int GPS_REQUEST_CODE = 124;
    private EditText mEtInput;
    private RadioButton mRbCity;
    private BDLocation mLocation;
    private SuggestionSearch mSuggestionSearch;
    private OnGetSuggestionResultListener mListener;
    private RelativeLayout mRlExhibition;
    private RecyclerView mReExhibition;
    private TextView mTvConfirm;
    private List<SuggestionResult.SuggestionInfo> mInfolist = new ArrayList<>();
    private MyAdapter mAdapter;
    private SuggestionResult.SuggestionInfo mSubmissionPosition;
    List<HotCity> hotCities = new ArrayList<>();
    boolean searchFlag = true;
    private MyLocationListener myLocationListener;
    private DistrictSearch mdistrictsearch;
    private boolean select = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN//主体占据全部屏幕，但不隐藏状态栏，这里的layout可以理解为内容主体.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);// 保持内容主体位置不变，不随着Systembar的隐藏显示而偏移
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//透明状态栏
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//适配刘海屏
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }
        setContentView(R.layout.activity_map);
        mTitle = findViewById(R.id.title);
        mBack = findViewById(R.id.iv_back);
        mEtInput = findViewById(R.id.et_input);
        mRbCity = findViewById(R.id.rb_city);
        mMapView = findViewById(R.id.bmapView);
        mRlExhibition = findViewById(R.id.rl_exhibition);
        mReExhibition = findViewById(R.id.re_exhibition);
        mRbCity.setButtonDrawable(new BitmapDrawable(null, ""));
        mTvConfirm = findViewById(R.id.tv_confirm);
        mLocationClient = new LocationClient(getApplicationContext());
        //动态计算状态栏高度并设置标题边距
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mTitle.getLayoutParams();
        params.topMargin = StatusBarUtil.getStatusBarHeight(this);
        mTitle.setLayoutParams(params);
        initView();
        getPersimmions();
    }

    private boolean checkGpsIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    private void openGPSSEtting() {
        if (checkGpsIsOpen()) {
            initLocation();
        } else {
            new AlertDialog.Builder(this).setTitle("开启 GPS")
                    .setMessage("您需要开启手机GPS功能使地图能正常运行，取消会使定位功能缺失")
                    //  取消选项
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Toast.makeText(MapActivity.this, "无法正常使用定位功能", Toast.LENGTH_SHORT).show();
                            // 关闭dialog
                            dialogInterface.dismiss();
                        }
                    })
                    //  确认选项
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //跳转到手机原生设置页面
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, GPS_REQUEST_CODE);
                        }
                    })
                    .setCancelable(false)
                    .show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE) {
            openGPSSEtting();
        }
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            } else {
                openGPSSEtting();
            }
        } else {
            openGPSSEtting();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        openGPSSEtting();
    }

    private void initView() {
        hotCities.add(new HotCity("北京", "北京", "101010100")); //code为城市代码
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));
        //城市选择
        mRbCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityPicker.from(MapActivity.this) //activity或者fragment
                        .enableAnimation(true)    //启用动画效果，默认无
                        .setAnimationStyle(R.style.DefaultCityPickerAnimation)    //自定义动画
                        .setLocatedCity(null)  //APP自身已定位的城市，传null会自动定位（默认）.setHotCities(hotCities)	//指定热门城市
                        .setOnPickListener(new OnPickListener() {
                            @Override
                            public void onPick(int position, City data) {
                                //Toast.makeText(getApplicationContext(), data.getName(), Toast.LENGTH_SHORT).show();
                                mRbCity.setText(data.getName());
                                mdistrictsearch.searchDistrict(new DistrictSearchOption().cityName(data.getName()));
                            }

                            @Override
                            public void onCancel() {
                                //Toast.makeText(getApplicationContext(), "取消选择", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onLocate() {
                                select = true;
                                mLocationClient.start();
                                /*//定位接口，需要APP自身实现，这里模拟一下定位
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        //定位完成之后更新数据
                                        CityPicker.from(MapActivity.this).locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                                    }
                                }, 3000);*/
                            }
                        })
                        .show();
            }
        });
        mdistrictsearch = DistrictSearch.newInstance();
        mdistrictsearch.setOnDistrictSearchListener(new OnGetDistricSearchResultListener() {
            @Override
            public void onGetDistrictResult(DistrictResult districtResult) {
                if (districtResult == null || districtResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    Log.d("districtresout", "no resout");
                    return;
                }
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(districtResult.centerPt)
                        .zoom(14)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                OverlayOptions dotOption = new DotOptions().center(districtResult.centerPt).color(0xAAA9A9A9);
                mBaiduMap.addOverlay(dotOption);
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.animateMapStatus(mMapStatusUpdate);
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mReExhibition.setLayoutManager(manager);
        mReExhibition.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter = new MyAdapter(MapActivity.this, mInfolist);
        //地址点选监听
        mAdapter.setOnMapItemClickListener(new OnMapItemClickListener() {
            @Override
            public void onClick(int position) {
                Log.e("wu", position + "");
                searchFlag = false;
                //地图SDK处理
                mBaiduMap.clear();
                LatLng ll = new LatLng(mInfolist.get(position).pt.latitude, mInfolist.get(position).pt.longitude);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                //定义Maker坐标点
                LatLng point = new LatLng(mInfolist.get(position).getPt().latitude, mInfolist.get(position).getPt().longitude);
                //构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
                //构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                //在地图上添加Marker，并显示
                mBaiduMap.addOverlay(option);
                mSubmissionPosition = mInfolist.get(position);
                mRlExhibition.setVisibility(View.GONE);

                mEtInput.setText(mSubmissionPosition.key);
                mEtInput.setSelection(mEtInput.getText().length());


            }
        });
        mReExhibition.setAdapter(mAdapter);
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                FlutterPluginCounter.send.success("back");

            }
        });
        //搜索监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mListener = new OnGetSuggestionResultListener() {
            @Override
            public void onGetSuggestionResult(SuggestionResult suggestionResult) {
                //处理sug检索结果
                Log.e("wu", suggestionResult.error.toString());
                if (suggestionResult.getAllSuggestions() != null) {
                    if (mInfolist.size() > 0) {
                        mInfolist.clear();
                    }
                    mAdapter.notifyDataSetChanged();
                    mRlExhibition.setVisibility(View.VISIBLE);
                    for (SuggestionResult.SuggestionInfo suggestionInfo : suggestionResult.getAllSuggestions()) {
                        Log.e("wu", suggestionInfo.toString());
                        if (suggestionInfo.pt != null) {
                            mInfolist.add(suggestionInfo);
                        }

                    }
                } else {
                    mRlExhibition.setVisibility(View.GONE);
                }
            }
        };
        mSuggestionSearch.setOnGetSuggestionResultListener(mListener);
        /*mEtInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 当按了搜索之后关闭软键盘
                    InputMethodManager manager = (InputMethodManager) MapActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    manager.hideSoftInputFromWindow(mEtInput.getWindowToken(), 0);
                    mAdapter.setIndex(-1);
                    mSuggestionSearch.requestSuggestion(new SuggestionSearchOption().city(mTvCity.getText().toString()).keyword(mEtInput.getText().toString()));
                    return true;
                }
                return false;
            }
        });*/
        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.e("wuhang", s.toString());
                if (searchFlag == true) {
                    mAdapter.setIndex(-1);
                    mSuggestionSearch.requestSuggestion(new SuggestionSearchOption().city(mRbCity.getText().toString()).keyword(mEtInput.getText().toString()));
                } else {
                    searchFlag = true;
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mTvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Gson gson = new Gson();
//                String jsonObject = gson.toJson(mSubmissionPosition);
                if (mSubmissionPosition != null) {
                    FlutterPluginCounter.send.success("ok");//纬度
                    FlutterPluginCounter.send.success("latitude," + mSubmissionPosition.pt.latitude);//纬度
                    FlutterPluginCounter.send.success("longitude," + mSubmissionPosition.pt.longitude);
                    FlutterPluginCounter.send.success("city," + mSubmissionPosition.city);
                    FlutterPluginCounter.send.success("district," + mSubmissionPosition.district);
                    FlutterPluginCounter.send.success("key," + mSubmissionPosition.key);
                    finish();
                } else {
                    Toast.makeText(MapActivity.this, "请选择地点", Toast.LENGTH_LONG).show();
                }

            }
        });


    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        //通过LocationClientOption设置LocationClient相关参数
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setOpenGps(true);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        select = false;
        mLocationClient.start();
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        FlutterPluginCounter.send.success("back");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(myLocationListener);
            mLocationClient.stop();
            mLocationClient = null;
        }
        mSuggestionSearch.destroy();
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;

    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                Log.e("baidu", "定位回调null");
                return;
            }
            if (select) {
                CityPicker.from(MapActivity.this)
                        .locateComplete(new LocatedCity(location.getCity().substring(0, location.getCity().length() - 1), location.getProvince(), location.getCityCode()),
                                LocateState.SUCCESS);
            } else {
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(location.getDirection()).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                Log.e("baidu", "定位回调");
                // 设置定位数据
                mBaiduMap.setMyLocationData(locData);
                //地图SDK处理
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                LatLng point = new LatLng(location.getLatitude(), location.getLongitude());
                OverlayOptions dotOption = new DotOptions().center(point).color(0xAAA9A9A9);
                mBaiduMap.addOverlay(dotOption);
                mLocation = location;
                mRbCity.setText(location.getCity().substring(0, location.getCity().length() - 1));
            }
            mLocationClient.stop();
        }

    }

}

